import hashlib
from typing import List
from paillier import encryption
from gmpy2 import mpz
from threshold_paillier import encrypt

class BloomFilter:
    def __init__(self, m_bits: int, k_hashes: int):
        self.storage = [False] * m_bits
        self.m_bits = m_bits
        self.k_hashes = k_hashes

    def insert(self, element: int):
        for i in range(self.k_hashes):
            index = self.hash(element, i + 1) % self.m_bits
            self.storage[index] = 1  # 设置为1

    def contains(self, element: int) -> bool:
        for i in range(self.k_hashes):
            index = self.hash(element, i + 1) % self.m_bits
            if self.storage[index] == 0:  # 这里也使用0
                return False
        return True

    def invert(self):
        self.storage = [(bit + 1) % 2 for bit in self.storage]  # 使用整数反转

    def encrypt_all(self, public_key) -> List[int]:
        ciphertexts = []
        for element in self.storage:
            ciphertexts.append(self.encrypt(int(element), public_key))
        return ciphertexts


    def paillier_encrypt_all(self, public_key_n, public_key_h) -> List[int]:
        EIBF = []  # 创建一个空列表来存储加密后的结果
        for element in self.storage:
            # 对每个元素进行加密，并将结果添加到 ciphertexts 列表中
            encrypted_value = encryption(int(element), public_key_n, public_key_h)
            EIBF.append(encrypted_value)
        return EIBF  # 返回加密后的结果列表

    def threshold_paillier_encrypt_all(self, public_key) -> List[int]:
        EIBF = []
        for element in self.storage:
            # 对每个元素进行加密，并将结果添加到 ciphertexts 列表中
            encrypted_value = encrypt(int(element), public_key)
            EIBF.append(encrypted_value)
        return EIBF  # 返回加密后的结果列表
    '''def paillier_encrypt_all(self, public_key_n,public_key_h) -> List[int]:
        #ciphertexts = []
        for element in self.storage:
            #ciphertexts.append(encryption(int(element), public_key_n,public_key_h))
            c = encryption(int(element), public_key_n,public_key_h)
        return c'''


    @staticmethod
    def hash(input: int, seed: int) -> int:
        # 使用 hashlib 生成 MurmurHash3 的替代
        input_bytes = input.to_bytes((input.bit_length() + 7) // 8, byteorder='big')
        hasher = hashlib.md5()  # 使用 MD5 作为示例
        hasher.update(input_bytes + seed.to_bytes(4, byteorder='big'))
        return int.from_bytes(hasher.digest()[:4], byteorder='big')

    def encrypt(self, element: int, public_key) -> int:
        # 这里需要实现实际的加密逻辑，下面是一个占位符
        return element  # 替换为实际加密实现
    def paillier_encrypt(self, element: int, public_key_n,public_key_h) -> int:
        # 这里需要实现实际的加密逻辑，下面是一个占位符
        return encryption(element,public_key_n,public_key_h)  # 替换为实际加密实现

    '''def print_bloom_filter(self):
        print("Bloom Filter storage:")
        print(self.storage)'''

    def print_bloom_filter(self):
        # 输出存储内容，将 True 显示为 1，False 显示为 0
        print('Bloom Filter:', ' '.join(['1' if bit else '0' for bit in self.storage]))